<?php
/**
* 微信 model
*/
class Weixin_model extends MY_Model
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('Curl_model','curl');
  		$this->appid='wx554ae3d8bd178aef';
  		$this->appsecret='f61e29965170fa0816e470aeed345b03';
	}

	/**
	 * 用户同意授权，获取code
	 */
	function header(){
		$backUrl=base_url().'Weixin/Weixin/accessBack';
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".($this->appid)."&redirect_uri=".urlencode($backUrl)."&response_type=code&scope=snsapi_userinfo&state=testtest#wechat_redirect";
		redirect($url);
	}

	/**
     * 通过code换取网页授权access_token，并且获取用户信息
     */
	function getUserInfo($code=''){
		$tokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".($this->appid).'&secret='.($this->appsecret)."&code={$code}"."&grant_type=authorization_code";  
	    $result = $this->curl->_get($tokenUrl);

		//拉取用户信息
		$accessToken=isset($result['access_token'])?$result['access_token']:'';
		$openId=isset($result['openid'])?$result['openid']:'';
		$userUrl="https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
		$userInfo = $this->curl->_get($userUrl);

		return $userInfo;
	}

	/**
     * 获取用户基本信息(UnionID机制)
     */
	function getUserInfoByUnionID($openid=''){
		// 获取access_token
		$accessToken=$this->getAccessToken();
		$unionUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openid}&lang=zh_CN";  
	    $result = $this->curl->_get($unionUrl);

		return $result;
	}

	/**
     * 获取access_token
     */
	function getAccessToken(){
		$id='1';
		$tokenInfo=$this->db->select('*')->where(array('id' => $id))->get('token')->row_array();

		if(empty($tokenInfo)||(isset($tokenInfo['token_time']) && (!$tokenInfo['token_time'] || ($tokenInfo['token_time']<time()) ) )){
			$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.($this->appid).'&secret='.($this->appsecret);
		    $result = $this->curl->_get($url);

		    $access_token=isset($result['access_token'])?$result['access_token']:'';
		    $operateData = array(
				'access_token' => $access_token,
				'token_time' => time()+7000,
				'tokentime' => date("Y-m-d H:i:s", time()+7000),
				);
		    if(empty($tokenInfo)){
				$this->db->insert('token',$operateData);
				return $access_token;
		    }else{
		    	$this->db->where(array('id' => $id))->update('token',$operateData);
				return $access_token;
		    }
		}else{
			$access_token=isset($tokenInfo['access_token'])?$tokenInfo['access_token']:'';
			return $access_token;
		}
	}

	/**
	 * 生成随机字串
	 */
	function getRandom($length='32'){
		$strings = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
		$res='';  
		for ( $i = 0; $i < $length; $i++ )  {  
			$res.= substr($strings,rand(0,$length),1);  
		}  
		return $res;  
	}

	/**
	 * 获取 jsapi_ticket
	 */
	function getJsapiTicket(){
		$id='1';
		$tokenInfo=$this->db->select('*')->where(array('id' => $id))->get('token')->row_array();
		if(empty($tokenInfo)||(isset($tokenInfo['ticket_time']) && (!$tokenInfo['ticket_time'] || ($tokenInfo['ticket_time']<time()) ) )){
			// 获取access_token
			$accessToken=$this->getAccessToken();
			// http GET方式请求获得jsapi_ticket
			$jspUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
			$result = $this->curl->_get($jspUrl);

			$ticket=isset($result['ticket'])?$result['ticket']:'';
		    $operateData = array(
				'ticket' => $ticket,
				'ticket_time' => time()+7000,
				'tickettime' => date("Y-m-d H:i:s", time()+7000),
				);
		    if(empty($tokenInfo)){
				$this->db->insert('token',$operateData);
				return $ticket;
		    }else{
		    	$this->db->where(array('id' => $id))->update('token',$operateData);
				return $ticket;
		    }
		}else{
			$ticket=isset($tokenInfo['ticket'])?$tokenInfo['ticket']:'';
			return $ticket;
		}
	}

	/**
	 * JS-SDK使用权限签名算法
	 */
	function getSignature($url=''){
		$noncestr=$this->getRandom();
		$jsapi_ticket=$this->getJsapiTicket();
		$timestamp=time();
		$signatureUrl="jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
		$shaSignatureUrl=sha1($signatureUrl);

		$result = array(
			  'appId'     => ($this->appid),
			  'timestamp' => $timestamp,
			  'nonceStr'  => $noncestr,
			  'signature' => $shaSignatureUrl,
			);
		return $result; 
	}
}
